package dbspo

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
	"fmt"
)

type JsonField json.RawMessage

func (j *JsonField) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
	}

	result := json.RawMessage{}
	err := json.Unmarshal(bytes, &result)
	*j = JsonField(result)
	return err
}

func (j JsonField) Value() (driver.Value, error) {
	if len(j) == 0 {
		return nil, nil
	}
	return json.RawMessage(j).MarshalJSON()
}

func (j JsonField) MarshalJSON() ([]byte, error) {
	if j == nil {
		return []byte("null"), nil
	}

	message := json.RawMessage(j)
	return message.MarshalJSON()
}

type Model struct {
	ID      uint64    `json:"id"`
	Pid     uint64    `json:"pid"`
	Name    string    `json:"name" gorm:"size:50"`
	Content JsonField `gorm:"type:json"`
	Product Product   `json:"-" gorm:"foreignkey:Pid"`
}

func (m *Model) TableName() string {
	return "ht_model"
}
